﻿using System.Collections.Generic;
using System.Linq;
using HappyBa.Core.Data;
using HappyBa.Core.Interfaces;

namespace HappyBa.Core.Statistics
{
    public class DevelopersTasksStatistics : IStatisticsCalculator
    {
        public IEnumerable<string> Calculate(StatisticsContext context)
        {
            foreach (var user in context.Metrics.Users.Where(x=>context.Metrics.IsDeveloper(x) && context.ActiveEmployees.Contains(x.ToString())))
            {
                var works = context.Metrics.Tasks.Cast<UIEstimatableEntityBase>()
                    .Concat(context.Metrics.Bugs)
                    .Where(context.Metrics.IsFinished)
                    .Where(x => x.Assignments.Any(y => y.GeneralUser.Id == user.Id))
                    .ToArray();
                yield return string.Format("{0}: Tasks done: {1}, Bugs fixed: {2} {3}", 
                    user, 
                    works.Count(context.Metrics.IsTask), 
                    works.Count(context.Metrics.IsBug),
                    GetAverageExecutionTime(user, works));
            }
        }

        private string GetAverageExecutionTime(User user, IList<UIEstimatableEntityBase> works)
        {
            works = works.Where(x => x.Effort > 0).ToArray();
            if (!works.Any()) return string.Empty;
            var effort = works.Sum(x => x.Effort);
            return string.Format(", Average task execution time: {0:0.##}%", works.Sum(x => x.TimeSpent) / effort * 100);
        }
    }
}
